package com.example.project.projectspringcloud.controller.admin.sysconfig;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Area;
import com.example.project.projectspringcloud.service.sys.SysAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(value = "后台系统区域数据控制器")
@Controller
@RequestMapping(value = "/admin/area")
public class AdminSysAreaController {

    @Autowired
    private SysAreaService sysAreaService;

    @ApiOperation(value = "系统区域管理", notes = "返回系统区域管理列表")
    @RequestMapping(value = {"", "/list"}, method = {RequestMethod.GET, RequestMethod.POST})
    public String list(Area area, Page page, Model model) {
        List<Area> areas = sysAreaService.list(area, null);
        model.addAttribute("page", new Page<Area>(areas));
        model.addAttribute("area", area);
        return "admin/sysconfig/sys-area-list";
    }

    @ApiOperation(value = "API系统区域列表", notes = "返回系统区域列表")
    @GetMapping(value = "/api/list")
    @ResponseBody
    public RespBody list(Area area) throws Exception {
        List<Area> areas = sysAreaService.list(area, null);
        return RespBody.ok(areas);
    }

    @ApiOperation(value = "API更改地区可用", notes = "管理员控制地区是否可用")
    @PostMapping(value = "/api/change_show")
    @ResponseBody
    public RespBody changeShow(Area area) {
        try {
            boolean result = sysAreaService.changeShow(area);
            if (!result) {
                return RespBody.error(Constants.Message.SAVE_FAILED);
            }
        } catch (OperationException e) {
            return RespBody.error(e.getMessage());
        }

        return RespBody.ok(Constants.Message.SAVE_SUCCESS);
    }
}
